﻿using UnityEngine;
using System.Collections.Generic;
using LitJson;

//本地玩家输入
public class LocalController : MonoBehaviour
{
    Transform cameraTrs;
    private Player localPlayer;
    private Vector2 lastDirect = Vector2.zero;   
    private void Start()
    {
        //获取主相机，并设置到主角身上
        cameraTrs = Camera.main.transform;
        cameraTrs.SetParent(transform);
        cameraTrs.localPosition = new Vector3(0, 6, -6);
        cameraTrs.localEulerAngles = new Vector3(30, 0, 0);

        //获取主角的Player脚本
        localPlayer = this.GetComponent<Player>();
    }
    void FixedUpdate()
    {
        if (localPlayer)
        {
            float dx = Input.GetAxisRaw("Horizontal");
            float dy = Input.GetAxisRaw("Vertical");
            //float mx = Input.GetAxis("Mouse X");
            Vector2 direct = new Vector2(dx,dy);
            
            if (lastDirect!=direct)
            {
                lastDirect = direct;
                MoveData data = new MoveData();
                data.username = localPlayer.userData.username;
                data.direct = direct;
                data.position = localPlayer.transform.position;
                data.rotation = localPlayer.transform.eulerAngles;

                string json = JsonUtility.ToJson(data);       
                NetworkManager.Instance.SendMessage(Protocol.PlayerMove_CMD,json);
            }

            localPlayer.Move(direct);          
        }
    }

    float elapse = 0;
    private void Update()
    {
        if (!localPlayer)
        {
            return;
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            elapse = 0;
        }
        if (Input.GetKey(KeyCode.Space))
        {
            elapse += Time.deltaTime;
            localPlayer.SetArrowLength(elapse*10);
        }
        if (Input.GetKeyUp(KeyCode.Space))
        {
            if (elapse>0.5f)
            {
                float force = elapse * 10;
                localPlayer.Fire(force,true);

                FireData data = new FireData();
                data.username = localPlayer.userData.username;
                data.force = force;

                NetworkManager.Instance.SendMessage(Protocol.PlayerFire_CMD,JsonUtility.ToJson(data));
            }
            elapse = 0;
            localPlayer.SetArrowLength(0);
        }
    }
}
